package com.hopu.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopu.domain.Menu;
import com.hopu.domain.RoleMenu;
import com.hopu.entity.PageEntity;
import com.hopu.entity.ResponseEntity;
import com.hopu.service.IMenuService;
import com.hopu.service.IRoleMenuService;
import com.hopu.utils.IconFontUtils;
import com.hopu.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IRoleMenuService roleMenuService;

    @RequestMapping("/tolistPage")
    public String toMenuListPage(){
        return "admin/menu/menu_list";
    }
    @RequestMapping("/list")
    @ResponseBody
    public PageEntity list(){
        List<Menu> pids = menuService.list(new QueryWrapper<Menu>().eq("pid", "0"));
        List<Menu> menus = new ArrayList();
        findChild(pids,menus);
        return new PageEntity(menus.size(),menus);
    }

    private void findChild(List<Menu> pids,List<Menu> menus){
        for (Menu menu:pids){
            if (!menus.contains(menu)){
                menus.add(menu);
            }
            List<Menu> childs = menuService.list(new QueryWrapper<Menu>().eq("pid",menu.getId()));
            menu.setNodes(childs);
            if (childs.size()>0){
                findChild(childs,menus);
            }
        }
    }

    /**
     * 向添加页面跳转
     */
    @RequestMapping("/toAddPage")
    public String toAddPage(Model model){
        //父级菜单
        List<Menu> list = menuService.list(new QueryWrapper<Menu>(new Menu()).eq("pid", '0'));
        findChildrens(list);

        //图标
        List<String> iconFont = IconFontUtils.getIconFont();

        model.addAttribute("iconFont", iconFont);
        model.addAttribute("list", list);
        return "admin/menu/menu_add";
    }
    private void findChildrens(List<Menu> list){
        for (Menu menu : list) {
            List<Menu> list2 = menuService.list(new QueryWrapper<Menu>(new Menu()).eq("pid", menu.getId()));
            if (list2!=null) {
                menu.setNodes(list2);
            }
        }
    }
    @RequestMapping("/save")
    @ResponseBody
    public ResponseEntity save(Menu menu){
        menu.setId(UUIDUtils.getID());
        menu.setCreateTime(new Date());
        menuService.save(menu);
        return ResponseEntity.success("添加菜单成功");
    }

    /**
     * 跳转修改界面
     */
    @RequestMapping("/toUpdatePage")
    public String adminPage(String id, Model model){
        Menu menu = menuService.getById(id);
        model.addAttribute("menu", menu);

        List<Menu> list = menuService.list(new QueryWrapper<Menu>(new Menu()).eq("pid", '0').orderByAsc("seq"));
        findChildrens(list);

        //图标
        List<String> iconFont = IconFontUtils.getIconFont();

        model.addAttribute("iconFont", iconFont);
        model.addAttribute("list", list);
        return "admin/menu/menu_update";
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    public ResponseEntity updateMenu(Menu menu){
        menu.setUpdateTime(new Date());
        menuService.updateById(menu);
        return ResponseEntity.success();
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity MenuDelete(@RequestBody List<Menu> menus){
        ArrayList<String> list = new ArrayList<>();
        for (Menu menu:menus){
            list.add(menu.getId());
        }
        menuService.removeByIds(list);
        return ResponseEntity.success("成功删除菜单");
    }

    @RequestMapping("/MenuList")
    @ResponseBody
    public PageEntity menuList(String id){
        // 查询当前角色已经关联了的权限
        List<RoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenu>().eq("role_id", id));

        // 如果不涉及到子菜单关联
        List<Menu> list = menuService.list();

        //  此处循环的作用就是为了判断角色已有权限，然后添加一个LAY_CHECKED字段，前端layui表格才能自动勾选
        ArrayList<JSONObject> jsonObjects = new ArrayList<>();
        list.forEach(menu -> {
            // 先需要把对象转换为JSON格式
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(menu));
            // 判断是否已经有了对应的权限
            List<String> menuIds = roleMenuList.stream().map(roleMenu -> roleMenu.getMenuId()).collect(Collectors.toList());
            if(menuIds.contains(menu.getId())){
                jsonObject.put("LAY_CHECKED",true);
            }
            jsonObjects.add(jsonObject);
        });

        return new PageEntity(jsonObjects.size(),jsonObjects);
    }
}
